<template>
  <div>
    <h1>App 根组件</h1>
    <my-table :data="goodsList">
      <!-- 表格的标题 -->
      <template #header>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>

      <!-- 表格每行的单元格 -->
      <template #body="{ row, index }">
        <td>{{ index + 1 }}</td>
        <td>{{ row.goods_name }}</td>
        <td>￥{{ row.goods_price }}</td>
        <td>
          <!-- 基于当前行的 inputVisible，来控制 input 和 button 的按需展
          示-->
          <input
            type="text"
            class="form-control form-control-sm ipt-tag form-ipt"
            v-if="row.inputVisible"
            v-focus
            v-model.trim="row.inputValue"
            @blur="handleAddTag(row)"
            @keyup.enter="handleAddTag(row)"
            @keyup.esc="row.inputValue = ''"
          />
          <!-- 添加标签的按钮 -->
          <button
            type="button"
            class="btn btn-primary btn-sm"
            v-else
            @click="row.inputVisible = true"
          >+Tag</button>
          <span class="badge badge-warning ml-2" v-for="item in row.tags" :key="item">{{ item }}</span>
        </td>
        <td>
          <button type="button" class="btn btn-danger btn-sm" @click="handleRemove(row.id)">删除</button>
        </td>
      </template>
    </my-table>
  </div>
</template>

<script>
import MyTable from './components/MyTable.vue'

export default {
  name: 'MyApp',
  components: {
    MyTable
  },
  directives: {
    // 封装自动获得焦点的指令
    focus(el) {
      el.focus()
    }
  },
  data() {
    return {
      // 商品列表
      goodsList: []
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 获取商品列表
    async getGoodsList() {
      const { data: res } = await this.$http.get('/api/goods')
      if (res.status !== 0) {
        return console.log('获取商品列表失败')
      }
      this.goodsList = res.data
      console.log(res.data)
    },
    // 删除某个商品
    handleRemove(id) {
      this.goodsList = this.goodsList.filter(item => item.id !== id)
    },
    // 新增标签
    handleAddTag(row) {
      // 先获取输入框的值暂存到 val 变量中
      const val = row.inputValue
      // 清空输入框的值
      row.inputValue = ''
      // 隐藏输入框
      row.inputVisible = false
      // 如果输入值为空或者标签内容已存在，则直接 return
      if (!val || row.tags.indexOf(val) !== -1) return
      row.tags.push(val)
    }
  }
}
</script>

<style lang="less" scoped>
.form-ipt {
  width: 80px;
  display: inline;
}
</style>
